using IdentityServer4.EntityFramework.Storage;
using IdentityServer4.Services;
using IdentityServer4.Stores;
using IdentityServer4.Validation;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using SJ.Platform.EFCore.Model;
using SJ.Platform.IdentityServer;
using SJ.Platform.Middleware.Middleware;
using System.Reflection;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

//注册数据库
builder.Services.AddDbContext<SJDBContext>(options =>
{
    options.UseMySql(builder.Configuration.GetConnectionString("MySqlConnection"), new MySqlServerVersion(new Version(6, 0, 31)));
});

////注入配置
builder.Services.AddIdentityServer()
    .AddDeveloperSigningCredential()
    .AddResourceOwnerValidator<CustomResourceOwnerPasswordValidator>()
    .AddInMemoryApiScopes(InMemoryConfiguration.ApiScopes)
    .AddInMemoryClients(InMemoryConfiguration.Clients)
    .AddInMemoryIdentityResources(InMemoryConfiguration.IdentityResources)
    .AddProfileService<CustomProfileService>();

builder.Services.AddScoped<IResourceOwnerPasswordValidator, CustomResourceOwnerPasswordValidator>();

//跨域
builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowSpecificOrigin",
        builder =>
        {
            builder.WithOrigins("https://localhost:7086") // 
                   .AllowAnyMethod()                // 
                   .AllowAnyHeader();               // 
        });
});

var app = builder.Build();


// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

//
app.UseCors("AllowSpecificOrigin");

//鉴权IdentityServer
app.UseIdentityServer();

app.UseAuthorization();

//注册中间件
app.UseMiddleware<ExceptionHandlingMiddleware>();

app.MapControllers();
app.MapGet("/", () => "Hello World!");
app.Run();
